package com.terrynoya.fight.combat
{
	import com.terrynoya.coreLib.MHashMap;
	import com.terrynoya.fight.char.Character;
	import com.terrynoya.fight.char.Entity;
	import com.terrynoya.fight.data.parser.sff.SpriteItem;
	import com.terrynoya.fight.evaluation.EvaluationSystem;
	import com.terrynoya.fight.io.FileSystem;
	import com.terrynoya.fight.stateMachine.StateSystem;
	import com.terrynoya.fight.system.camera.MCamera;
	import com.terrynoya.fight.system.camera.MCameraController;
	import com.terrynoya.geom.MVector2D;

	public class FightEngine
	{
		private var _stage:FightStage;
		
		private var _entities:EntityCollection;
		
		private var _combatChecker:CombatChecker;
		
		private var _stateSystem:StateSystem;
		private var _evalSystem:EvaluationSystem;
		
		private var _isPaused:Boolean;
		
		public function FightEngine(bgView:SpriteItem)
		{
			this._stage = new FightStage(this,bgView);
			this._entities = new EntityCollection(this);
			this._combatChecker = new CombatChecker(this);
			this._evalSystem = new EvaluationSystem();
			this._stateSystem = new StateSystem(this);
		}
		
		public function get camera():MCamera 
		{
			return this._stage.cameraContrl.camera;
		}
		
		public function globalToCamera(pos:MVector2D):MVector2D
		{
			return this._stage.cameraContrl.globalToCamera(pos);
		}
		
		/**
		 * 暂停 
		 * @param value
		 * 
		 */		
		public function set pause(value:Boolean):void 
		{
			this._isPaused = value;
		}
		
		public function get pause():Boolean 
		{
			return this._isPaused;
		}
		
		/**
		 * 单步调试 
		 * 
		 */		
		public function stepForward():void
		{
			if(!this._isPaused)
			{
				return;
			}
			this.updateForever(0);
		}
		
		public function getStates(input:String):MHashMap
		{
			return this._stateSystem.getStates(FileSystem.build(input));
		}
		
		public function get stateSystem():StateSystem
		{
			return _stateSystem;
		}

		public function get evalSystem():EvaluationSystem
		{
			return _evalSystem;
		}

		public function get stage():FightStage
		{
			return _stage;
		}

		public function get entities():EntityCollection
		{
			return _entities;
		}

		public function addEntity(value:Entity):void
		{
			this._entities.add(value);
		}
		
		public function update(time:int):void
		{
			if(this._isPaused)
			{
				return;
			}
			this.updateForever(time);
		}
		
		private function updateForever(time:int):void
		{
			this._entities.update(time);
			this._combatChecker.run();
			this.stage.update();
		}
		
		public function getCharacterById(id:String):Character
		{
			var rlt:Character = null;
			for (var i:int = 0; i < this.entities.length; i++) 
			{
				var entity:Entity = this.entities.getChildAt(i);
				var chara:Character = entity as Character;
				if(chara != null && chara.id == id)
				{
					rlt = chara;
					break;
				}
			}
			return rlt;
			
		}
	}
}